<?php

namespace app\service;

use app\ai\model\Task;
use app\ai\model\Template;
use app\ai\model\TemplatePrice;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\app\logic\system\SystemConfigLogic;
use plugin\saiadmin\utils\Arr;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class AiService
{

    /**
     * 读取配置
     * @return array|mixed|null
     */
    public static function getConfig()
    {
        $logic = new SystemConfigLogic();
        $config = $logic->getGroup('ai_config');
        if (!$config) {
            throw new ApiException('未设置AI配置');
        }
        return $config;
    }

    /**
     * 创建AI任务订单
     * @param int $uid 用户ID
     * @param array $data 任务数据
     * @return array
     */
    public static function createTask($uid, $data)
    {
        try {
            // 生成唯一任务号
            $taskNo = date('YmdHis') . mt_rand(1000, 9999);

            // 创建任务
            $task = Task::create([
                'uid' => $uid,
                'task_no' => $taskNo,
                'template_id' => $data['template_id'],
                'articulation'=> $data['articulation'] ?? '1',
                'original_img_url' => $data['original_img_url'],
                'original_mask_url' => $data['original_mask_url'] ?? '',
                'manual' => $data['manual'] ?? 2,
                'remarks' => $data['remarks'] ?? '',
                'create_time' => date('Y-m-d H:i:s'),
                'prompt_id' => $data['prompt_id'] ?? '',
                'submission_status' => 1, // 待提交
                'task_status' => 1,      // 排队中
                'retry_count' => 0,
                'is_share' => 0,
                'view' => 0,
                'check_status' => 1      // 默认审核通过
            ]);

            return [
                'task_no' => $taskNo,
                'task_id' => $task->id
            ];
        } catch (\Exception $e) {
            throw new ApiException($e->getMessage());
        }
    }


    /**
     * 提交任务 到服务端
     * @param $taskNo
     * @return array
     */
    public static function submitServe($taskNo)
    {
        $config = static::getConfig();
        $host = Arr::getConfigValue($config, 'host');
        if (!$host) {
            throw new ApiException("无法读取主机地址");
        }

        if (!preg_match('/^https?:\/\//', $host)) {
            throw new ApiException("主机地址必须以http或https开头");
        }

        if (!filter_var($host, FILTER_VALIDATE_URL)) {
            throw new ApiException("主机地址格式不正确");
        }

        // 查找任务
        $task = Task::where('task_no', $taskNo)->find();
        if (!$task) {
            throw new ApiException('任务不存在');
        }

        // 检查任务状态
        if ($task->submission_status != 1) {
            throw new ApiException('任务已提交');
        }

        if($task->manual == 1){
            $manual = true;
        }else{
            $manual = false;
        }
        
        $requestData = [
            'task_id' => $task->task_no,
            'original_img_url' => $task->original_img_url,
            'original_mask_url' => $task->original_mask_url,
            'template_id' => $task->template_id,
            'articulation' => $task->articulation,
            'manual' => $manual,
        ];

        try {
            $client = new Client([
                'timeout' => 30,  // 设置30秒超时
                'verify' => true // 如果需要忽略SSL证书验证
            ]);

            $response = $client->post($host, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'token' => self::encrypt()
                ],
                'json' => $requestData
            ]);

            $result = json_decode($response->getBody()->getContents(), true);
            
            // 更新任务状态
            $task->submission_status = 2; // 已提交
            $task->save();

            return $result;
        } catch (RequestException $e) {
            if ($e->hasResponse()) {
                $error = json_decode($e->getResponse()->getBody()->getContents(), true);
                throw new ApiException($error['message'] ?? $e->getMessage());
            }
            throw new ApiException('请求失败：' . $e->getMessage());
        }
    }


    //获取加密 Token
   private static function encrypt() {
        $config = static::getConfig();
        $key = Arr::getConfigValue($config, 'key');
        if (!$key) {
            throw new Exception("无法读取密钥");
        }
    
        if (!preg_match('/^[A-Za-z\d@$!%*?&^]{16}$/', $key)) {
            throw new Exception("密钥必须为16位且仅包含字母、数字或特殊符号。");
        }
    
        // 生成16位随机字符串作为明文
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $plaintext = '';
        for ($i = 0; $i < 16; $i++) {
            $plaintext .= $characters[rand(0, strlen($characters) - 1)];
        }
    
        // 生成随机IV
        $iv = openssl_random_pseudo_bytes(16);
    
        // 使用PKCS7填充
        $block_size = 16;
        $pad_length = $block_size - (strlen($plaintext) % $block_size);
        $plaintext .= str_repeat(chr($pad_length), $pad_length);
    
        // 加密
        $encrypted = openssl_encrypt(
            $plaintext,
            'AES-128-CBC',
            $key,
            OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING,
            $iv
        );
    
        // 组合IV和加密数据并进行base64编码
        return base64_encode($iv . $encrypted);
    }
}
